import React, {useRef, useState} from "react";

function EditPassword() {

  const veriInput = useRef<any>()
  const newInput = useRef<any>()

  // 职责范围：输入认证密码，确认密码
  const [veriWidth, setVeriWidth] = useState(0)      // 显示
  const [veriPlacehd, setVeriPlacehd] = useState('')     // placeholder
  const [veriVal, setVeriVal] = useState('')     // 值
  // 职责范围：输入新密码
  const [newWidth, setNewWidth] = useState(0)      // 显示
  const [newPlacehd, setNewPlacehd] = useState('')     // placeholder
  const [newVal, setNewVal] = useState('')     // 值
  // 一个按钮完成全部功能
  const [buttonState, setButtonState] = useState(0)
  // 按钮的逻辑状态： 0-弹出确认密码
  // 1-提交确认密码
  // 2-提交修改后的密码
  const [buttonText, setButtonText] = useState('修改密码')
  const [buttonClass, setButtonClass] = useState('')

  function switchInput() {
    switch (buttonState) {
      // ================================
      // 默认状态，点击后显示认证密码输入框
      // ================================
      default:
        openInput('veri', '请输入原密码')
        changeBtn(1, '认证密码', '')
        veriInput.current.focus()
        return;

      // ===============================================================================
      // 确认状态，点击后提交确认密码，成功后显示新密码输入框，原认证密码框改变为确认密码输入框
      // ===============================================================================
      case 1:
        /* --- 认证部分 ------------------------ */
        console.log('[旧密码验证]', veriVal);
        verifyPwd().then(() => {
          changeBtn(1, '验证成功', 'success')
          setTimeout(() => {
            changeBtn(2, '提交新密码', '')
            openInput('new', '输入新密码')
            openInput('veri', '确认新密码')
            newInput.current.focus()
          }, 1000)
        }).catch(err => {
          changeBtn(1, err, 'error')
          setTimeout(() => {
            closeInput()
          }, 1000)
        })
        return;

      // ===========================================================
      // 修改密码状态，点击后提交新密码到服务器，修改成功后恢复到默认状态
      // ===========================================================
      case 2:
        /* --- 提交新密码部分 --- */
        if (veriVal !== newVal) {
          changeBtn(2, '两次输入的密码不一致', 'error')
          setTimeout(() => {
            changeBtn(2, '提交新密码', '')
          }, 1500)
          return;
        }
        editPwd().then(() => {
          changeBtn(2, '修改成功', 'success')
          setTimeout(() => {
            changeBtn(0, '修改密码', '')
            closeInput()
          }, 2000)
        }).catch(err => {
          changeBtn(2, err, 'error')
          setTimeout(() => {
            closeInput()
          }, 1000)
        })
        return;
    }
  }

  function changeBtn(state: any, text: any, className: any) {
    if (/^[0-2]$/.test(state))
      setButtonState(state)     // int     0, 1, 2
    if (text !== undefined)
      setButtonText(text)       // string  any
    if (className !== undefined)
      setButtonClass(className) // string  default, 'doing', 'error'
  }

  function openInput(btn: any, text: any) {
    switch (btn) {
      case 'veri':
        setVeriVal('')
        setVeriWidth(150)
        setTimeout(() => {
          setVeriPlacehd(text)
        }, 200)
        break;
      case 'new':
        setNewWidth(150)
        setTimeout(() => {
          setNewPlacehd(text)
        }, 200)
        break;
      default:
        break;
    }
  }

  function closeInput(btn?: any) {
    switch (btn) {
      case 'veri':
        setVeriPlacehd('')
        setVeriWidth(0)
        setVeriVal('')
        break;
      default:
        setVeriPlacehd('')
        setNewPlacehd('')
        setVeriWidth(0)
        setNewWidth(0)
        setVeriVal('')
        setNewVal('')
        break;
    }
    changeBtn(0, '修改密码', '')
  }

  function verifyPwd() {
    return new Promise((resolve, reject) => {
      console.log('[请求验证密码]');
      changeBtn(1, '验证中...', 'doing')
      /* cyGet('验证密码',
         cyUrl([baseURL, user.base, user.verifyPwd]),
         {
           token: wls.XB_token,
           password: veriVal
         }
       ).then(() => {
         resolve()
       }).catch(err => {
         reject(err)
       })*/
    })
  }

  function editPwd() {
    return new Promise((resolve, reject) => {
      console.log('[请求修改密码]');
      changeBtn(2, '修改中...', 'doing')
      /* cyPost('修改密码',
         cyUrl([baseURL, user.base, user.update]),
         {token: wls.XB_token},
         qs.stringify({password: newVal})
       ).then(() => {
         resolve()
       }).catch(err => {
         reject(err)
       })*/
    })
  }

  return (
    <>
      <input
        type="password"
        style={{
          borderColor: newWidth ? '#00C3FF' : 'transparent',
          backgroundColor: buttonState === 2 ? '' : 'transparent',
          width: `${newWidth}px`,
          padding: newWidth ? '0 6px' : '0',
          marginRight: newWidth ? '10px' : '0px'
        }}
        placeholder={newPlacehd}
        disabled={buttonClass ? true : false}
        onChange={(e) => {
          setNewVal(e.target.value)
        }}
        value={newVal}
        ref={newInput}
      />
      <input
        type="password"
        style={{
          borderColor: veriWidth ? '#00C3FF' : 'transparent',
          width: `${veriWidth}px`,
          padding: veriWidth ? '0 6px' : '0',
          marginRight: veriWidth ? '30px' : '0px'
        }}
        placeholder={veriPlacehd}
        disabled={buttonClass ? true : false}
        onChange={(e) => {
          setVeriVal(e.target.value)
        }}
        onBlur={(e) => {
          if (!e.target.value && buttonState !== 2) closeInput('veri')
        }
        }
        value={veriVal}
        ref={veriInput}
      />
      <button
        className={'button ' + buttonClass}
        disabled={buttonClass ? true : false}
        style={{marginLeft: veriWidth ? '0px' : '-2px'}}
        onClick={switchInput}
      >
        {buttonText}
      </button>
    </>
  )
}

export default EditPassword
